<?php
namespace app\Payment\version;

use app\Payment\model\TradeList;
use app\Payment\model\User;
use app\Payment\model\UserSecretkey;

abstract class VersionAbs
{
    public $parameter = [];  //用户提交过来的参数
    public $version_parameter_rule = [];
    public $version_parameter = []; //版本所有参数
    public $version_parameter_sign_rule = [];
    public $version_parameter_sign = []; //版本签名的参数
    public $secret_key = []; // 密钥
    public $memberid_name = ''; //用户编码
    public $orderid_name = ''; //交易订单号
    public $user_id = "";  //用户ID

    public function __construct(&$returnJson)
    {
        $this->parameter = &$returnJson;
        $this->SetMemberidOrderid();
        $this->GetSecretKey();
        $this->CheckUserStatus();
    }

    public function main()
    {
        $this->setVersionParameter($this->version_parameter_rule);
        $this->setVersionParameterSign($this->version_parameter_sign_rule);
        return (
            $this->setVersionParameterValue()
            && $this->setVersionParameterSignValue()
            && $this->CheckOrderid()
            && $this->CheckParameter($this->version_parameter,$this->parameter['msg'])
            && $this->CheckSign($this->version_parameter,$this->version_parameter_sign,$this->secret_key,$this->parameter['msg'])
            && $this->FormatData($this->version_parameter,$this->parameter['formatdata'],$this->parameter['msg'])
            && $this->ReturnData()
        );
    }


    /**
     * 判断赋值版本所有参数
     */
    private function setVersionParameterValue()
    {
        foreach($this->version_parameter_rule as $key => $value){
            if(array_key_exists($key,$this->parameter['parameter'])){
                if($this->parameter['parameter'][$key] == "" && $value == 'not_null'){
                    $this->parameter['msg'] = "参数：".$key.' 不能为空';
                    return false;
                }else{
                    $this->version_parameter[$key] = $this->parameter['parameter'][$key];
                }
            }else{
                if($value == 'not null'){
                    $this->parameter['msg'] = "缺少参数：".$key;
                    return false;
                }
            }
        }

        return true;
    }

    /**
     * 判断赋值版本签名参数
     */
    private function setVersionParameterSignValue()
    {
        foreach($this->version_parameter_sign_rule as $key => $value){
            if(array_key_exists($key,$this->parameter['parameter'])){
                if($this->parameter['parameter'][$key] == "" && $value == 'not_null'){
                    $this->parameter['msg'] = "参数：".$key.' 不能为空';
                    return false;
                }else{
                    $this->version_parameter_sign[$key] = $this->parameter['parameter'][$key];
                }
            }else{
                $this->parameter['msg'] = "缺少参数：".$key;
                return false;
            }
        }
        return true;
    }

    /**
     * 获取用户密钥
     */
    public function GetSecretKey(){
        if($this->memberid_name == '' || !array_key_exists($this->memberid_name,$this->parameter['parameter'])){
            $this->parameter['msg'] = '获取用户信息失败';
            return false;
        }else{
            $secrekey = UserSecretkey::where('memberid','=',$this->parameter['parameter'][$this->memberid_name])->findOrEmpty();
            if(!$secrekey->isEmpty()){
                $this->user_id = $secrekey->user_id;
//                $this->parameter['other']['user_id'] = $secrekey->user_id;
                $this->parameter['user_id'] = $secrekey->user_id;
                $this->secret_key = [
                    'memberid' => $secrekey->memberid,
                    'md5str' => $secrekey->md5str,  //MD5密钥
                    'sys_publickey' => $secrekey->sys_publickey,  //rsa 系统公钥
                    'sys_privatekey' => $secrekey->sys_privatekey, //rsa 系统私钥
                    'user_publickey' => $secrekey->user_publickey, //rsa 用户公钥
                    'user_privatekey' => $secrekey->user_privatekey, //rsa 用户公钥
                ];
                return true;
            }else{
                $this->parameter['msg'] = '获取用户密钥信息失败';
                return false;
            }
        }
    }

    /**
     * 判断交易订单号是否重复
     */
    public function CheckOrderid()
    {
        if($this->orderid_name == '' || !array_key_exists($this->orderid_name,$this->parameter['parameter'])){
            $this->parameter['msg'] = '交易订单号不能为空';
            return false;
        }else{
            $where_arr = [];
            if($this->parameter['orderid_repeat'] === 1){ //不同用户的用户订单号可以重复
                $where_arr = [
                    ['user_id','=',$this->user_id],
                    ['user_orderid','=',$this->parameter['parameter'][$this->orderid_name]]
                ];
            }elseif($this->parameter['orderid_repeat'] === 0){  //所有用户的用户订单号不可重复
                $where_arr = [
                    ['user_orderid','=',$this->parameter['parameter'][$this->orderid_name]]
                ];
            }
            $count = TradeList::where($where_arr)->lock(true)->count();
            if($count > 0){
                $this->parameter['msg'] = '交易订单号已存在';
                return false;
            }else{
                return true;
            }
        }
    }

    /**
     * 判断用户状态，是否可以调起支付接口
     * @return bool
     */
    public function CheckUserStatus()
    {
        $user_find = User::field('status,pay_status')->findOrEmpty($this->user_id);
        if($user_find->isEmpty()){
            $this->parameter['msg'] = "用户不存在";
            return false;
        }
        if($user_find->status != 2 || $user_find->pay_status != 0){
            $this->parameter['msg'] = "用户状态异常，支付功能被禁用，请联系管理员";
            return false;
        }else{
            return true;
        }
    }

    private function ReturnData(){
        if(array_key_exists('formatdata',$this->parameter)){
            $this->parameter['formatdata']['sign'] = payment_sha1($this->parameter['formatdata']);
            return true;
        }else{
            $this->parameter['msg'] = "系统错误，formatdata 格式化数据出错";
            return false;
        }
    }

    /**
     * 设置商户ID，用来获取相应的用户信息
     * @return mixed
     */
   abstract function SetMemberidOrderid();

    /**
     * 设置版本所有参数
     * @return mixed
     */
   abstract function setVersionParameter(&$parameter);

    /**
     * 设置版本签名参数
     * @return mixed
     */
   abstract function setVersionParameterSign(&$parameter);

}